/*
 * Copyright 2018 The JA-SIG Collaborative. All rights reserved.
 * distributed with thi file and available online at
 */
package com.lap.codegen.utils;

import java.io.File;
import java.io.IOException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import freemarker.template.TemplateExceptionHandler;

/**
 * @author 劳水生
 * @version 1.0.0
 */
public final class FreemarkerUtils {
	/**
	 * 日志输出
	 */
	private static final Logger LOGGER = LoggerFactory.getLogger(FreemarkerUtils.class);
	
	private FreemarkerUtils() {}

	/**
	 * 初始化freemarker模版信息
	 * 
	 * @param path
	 * @return
	 * @throws IOException
	 */
	public static Configuration getFreemarker(String path) throws IOException {
		Configuration cfg = new Configuration(Configuration.VERSION_2_3_22);
		cfg.setDirectoryForTemplateLoading(new File(path));
		cfg.setDefaultEncoding("UTF-8");
		cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
		return cfg;
	}

	/**
	 * <pre>
	 * 获取模版的内容信息
	 * </pre>
	 * 
	 * @param config
	 * @param name
	 * @param obj
	 * @return
	 */
	public static String getContent(Configuration config, String name, Object obj) {
		try {
			Template t = config.getTemplate(name);
			return FreeMarkerTemplateUtils.processTemplateIntoString(t, obj);
		} catch (IOException | TemplateException e) {
			LOGGER.error(e.getLocalizedMessage(), e);
		}
		return null;
	}
	
}
